import Flutter
import UIKit
import AdSupport
import AppTrackingTransparency
import WebKit
import CoreTelephony
import SystemConfiguration


@main
@objc class AppDelegate: FlutterAppDelegate {
    var time = 0
    
    override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        GeneratedPluginRegistrant.register(with: self)
        
        // 初始化广告SDK
        let controller = window?.rootViewController as? FlutterViewController
        if let controller = controller {
            let channel = FlutterMethodChannel(name: "com.weather.quickly.report", binaryMessenger: controller.binaryMessenger)
            channel.setMethodCallHandler { (call, result) in
                // 处理方法调用
                if call.method == "getInstallInfo" {
                    // 调用 iOS 原生方法获取设备信息（包含IDFA和归因数据）
                    self.getDeviceInfoWithAttribution(result: result)
                    
                } else if call.method == "getHealthScore" {
                    HealthScore().getHealthScore(result: result)
                }
                else {
                    result(FlutterMethodNotImplemented)
                }
            }
        }
        
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }
    
    // iOS 原生方法：获取设备信息（包含IDFA和归因数据）
    private func getDeviceInfoWithAttribution(result: @escaping FlutterResult) {
        let webUa = self.getCurrentUserAgent()
        // 1. 获取IDFA
        self.getIDFA { idfa in
            print("====   idfa \(idfa)")
            UserDefaults.standard.set(idfa, forKey: "idfa")
            //开始网络监听
            NetworkMonitor.shared().startMonitoring { _ in
                
            }
            NetworkMonitor.shared().networkStatusBlock = { status in
                print("====   网络状态是 \(status.rawValue)")
                if status != .unknown && status != .notReachable {
                    // 2. 获取归因数据
                    WsHcpADSHelper.getAppleAttribution { attrData in
                        // 3. 准备请求参数
                        var parameters = self.prepareInstallParameters(webUa: webUa, idfa: idfa)
                        
                        // 添加归因数据（如果有）
                        if let attrData = attrData {
                            print("====成功获取归因数据：\(attrData)")
                            parameters["iosAdsAttributeDataDTO"] = attrData
                        } else {
                            print("====获取归因数据失败，不传 iosAdsAttributeDataDTO")
                        }
                        print("请求URL  =====  https://api.luyini.cn/flibbert/obsequious")
                        print("请求参数 parameters ===== ",parameters)
                        // 4. 发送请求并返回结果给Flutter
                        self.sendInstallRequest(parameters: parameters) { responseData in
                            if let data = responseData["data"] as? [String:Any] {
                                if let iosToken = UserDefaults.standard.object(forKey: "token") as? String,
                                   let djId = data["djId"] as? String,
                                   let appId = data["app_id"] as? String {
                                    print("iosToken ==== \(iosToken)\n djId ==== \(djId)\n appId ==== \(appId)")
                                    self.sendTokenRequest(parameters: ["djId":djId,"appId":appId,"iosToken":iosToken]) { _ in
                                        
                                    }
                                }
                                
                                if let jsonData = try? JSONSerialization.data(withJSONObject: data, options: []),
                                   let jsonString = String(data: jsonData, encoding: .utf8) {
                                    
                                    
                                    
                                    result(jsonString)
                                } else {
                                    result(FlutterError(code: "JSON_ERROR",
                                                        message: "Failed to serialize response data",
                                                        details: nil))
                                }
                                
                            } else {
                                DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                                    self.sendInstallRequest(parameters: parameters) { responseData in
                                        if let data = responseData["data"] as? [String:Any] {
                                            
                                            if let iosToken = UserDefaults.standard.object(forKey: "token") as? String,
                                               let djId = data["djId"] as? String,
                                               let appId = data["app_id"] as? String {
                                                print("iosToken ==== \(iosToken)\n djId ==== \(djId)\n appId ==== \(appId)")
                                                self.sendTokenRequest(parameters: ["djId":djId,"appId":appId,"iosToken":iosToken]) { _ in
                                                    
                                                }
                                            }
                                            
                                            if let jsonData = try? JSONSerialization.data(withJSONObject: data, options: []),
                                               let jsonString = String(data: jsonData, encoding: .utf8) {
                                                result(jsonString)
                                            } else {
                                                result(FlutterError(code: "JSON_ERROR",
                                                                    message: "Failed to serialize response data",
                                                                    details: nil))
                                            }
                                            
                                        }  else {
                                            DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                                                self.sendInstallRequest(parameters: parameters) { responseData in
                                                    if let data = responseData["data"] as? [String:Any] {
                                                        
                                                        if let iosToken = UserDefaults.standard.object(forKey: "token") as? String,
                                                           let djId = data["djId"] as? String,
                                                           let appId = data["app_id"] as? String {
                                                            print("iosToken ==== \(iosToken)\n djId ==== \(djId)\n appId ==== \(appId)")
                                                            self.sendTokenRequest(parameters: ["djId":djId,"appId":appId,"iosToken":iosToken]) { _ in
                                                                
                                                            }
                                                        }
                                                        
                                                        if let jsonData = try? JSONSerialization.data(withJSONObject: data, options: []),
                                                           let jsonString = String(data: jsonData, encoding: .utf8) {
                                                            result(jsonString)
                                                        } else {
                                                            result(FlutterError(code: "JSON_ERROR",
                                                                                message: "Failed to serialize response data",
                                                                                details: nil))
                                                        }
                                                        
                                                    }  else {
                                                        result("error:网络请求失败");
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    
                    
                } else {
                    print("==== 没有网络====  网络状态是 \(status.rawValue) time = \(self.time)")
                    if !idfa.isEmpty&&self.time > 15 {
                        result("error:网络超时！！！！==== ")
                    } else {
                        // 延迟2秒执行
                        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                            print("延迟1秒执行的任务 ==== ")
                            self.time += 1
                            self.getDeviceInfoWithAttribution(result: result)
                        }
                        
                        
                    }
                }
            }
        }
        
    }
    
    // 获取当前用户代理
    private func getCurrentUserAgent() -> String {
        let webConfiguration = WKWebViewConfiguration()
        if let currentUA = webConfiguration.applicationNameForUserAgent {
            return currentUA
        }
        return "Unknown User Agent"
    }
    
    // 准备安装参数
    private func prepareInstallParameters(webUa: String, idfa: String) -> [String: Any] {
        return [
            "androidId": "",
            "appName": "个人所得税核算助手-PG",
            "appVersion": Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "1.0.0",
            "pkgName": "com.whlianta.tax.pg",
            "carrier": "0",
            "deviceIp": "",
            "deviceModel": DeviceUtil.getPhoneDeviceType() ?? "",
            "idfa": idfa,
            "idfv": "1",
            "installDatetime": Int(Date().timeIntervalSince1970),
            "mac": "",
            "networkAccess": self.getNetworkCode(),
            "oaId": DeviceUtil.getPAID() ?? "",
            "paid": DeviceUtil.getPAID() ?? "",
            "caid": "",
            "os": 1,
            "osVersion": UIDevice.current.systemVersion,
            "uaWebView": webUa,
            "downloadChannel": "APPLE"
        ]
    }
    
    // 发送安装请求
    private func sendInstallRequest(parameters: [String: Any], completion: @escaping ([String: Any]) -> Void) {
        guard let url = URL(string: "https://api.juzhangit.com/dfard/aqeadd") else {
            fatalError("Invalid Install URL")
        }
        

        
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
        request.httpBody = try? JSONSerialization.data(withJSONObject: parameters)
        
        URLSession.shared.dataTask(with: request) { data, _, error in
            if let error = error {
                print("Install 请求失败：\(error.localizedDescription)")
                completion(["code": 500, "msg": "Network error: \(error.localizedDescription)"])
                return
            }
            
            guard let data = data else {
                completion(["code": 500, "msg": "No data received"])
                return
            }
            
            do {
                if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
                    completion(json)
                } else {
                    completion(["code": 500, "msg": "Invalid JSON format"])
                }
            } catch {
                completion(["code": 500, "msg": "JSON parsing error: \(error.localizedDescription)"])
            }
        }.resume()
    }
    
    // 发送token请求
    private func sendTokenRequest(parameters: [String: Any], completion: @escaping ([String: Any]) -> Void) {
        guard let url = URL(string: "https://api.juzhangit.com/dfard/pgkblcrw") else {
            fatalError("Invalid Install URL")
        }
        
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
        request.httpBody = try? JSONSerialization.data(withJSONObject: parameters)
        
        URLSession.shared.dataTask(with: request) { data, _, error in
            if let error = error {
                print("=====sendTokenRequest 请求失败：\(error.localizedDescription)")
                completion(["code": 500, "msg": "Network error: \(error.localizedDescription)"])
                return
            }
            
            guard let data = data else {
                completion(["code": 500, "msg": "No data received"])
                return
            }
            
            do {
                if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
                    print("=====sendTokenRequest\(json) 请求成功")
                    completion(json)
                } else {
                    completion(["code": 500, "msg": "Invalid JSON format"])
                }
            } catch {
                completion(["code": 500, "msg": "JSON parsing error: \(error.localizedDescription)"])
            }
        }.resume()
    }
    
    // 获取IDFA（包含ATT授权流程）
    private func getIDFA(completion: @escaping (String) -> Void) {
        if #available(iOS 14, *) {
            ATTrackingManager.requestTrackingAuthorization { status in
                DispatchQueue.main.async {
                    switch status {
                    case .authorized:
                        print("Tracking is authorized")
                        let idfa = ASIdentifierManager.shared().advertisingIdentifier.uuidString
                        completion(idfa)
                    case .denied, .restricted:
                        print("Tracking is denied or restricted")
                        // 即使被拒绝，仍然可以获取IDFA（但可能都是0000...）
                        let idfa = ASIdentifierManager.shared().advertisingIdentifier.uuidString
                        completion(idfa)
                    case .notDetermined:
                        // 理论上不会到这里，因为我们已经请求了授权
                        let idfa = ASIdentifierManager.shared().advertisingIdentifier.uuidString
                        completion(idfa)
                    @unknown default:
                        fatalError("Unknown authorization status")
                    }
                }
            }
        } else {
            // iOS 14 以下版本不需要请求跟踪权限
            let idfa = ASIdentifierManager.shared().advertisingIdentifier.uuidString
            completion(idfa)
        }
    }
    
    // 获取网络类型代码
    func getNetworkCode()->Int{
        let type = self.getNetworkType()
        var ret = -1;
        if(type == "WiFi"){
            ret = 0
        }else if(type == "2G"){
            ret = 2
        }else if(type == "3G"){
            ret = 3
        }else if(type == "4G"){
            ret = 4
        }else if(type == "5G"){
            ret = 5
        }
        return ret
    }
    
    /// 获取网络类型
    func getNetworkType() -> String {
        var zeroAddress = sockaddr_storage()
        bzero(&zeroAddress, MemoryLayout<sockaddr_storage>.size)
        zeroAddress.ss_len = __uint8_t(MemoryLayout<sockaddr_storage>.size)
        zeroAddress.ss_family = sa_family_t(AF_INET)
        let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
            $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { address in
                SCNetworkReachabilityCreateWithAddress(nil, address)
            }
        }
        guard let defaultRouteReachability = defaultRouteReachability else {
            return "notReachable"
        }
        var flags = SCNetworkReachabilityFlags()
        let didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags)
        
        guard didRetrieveFlags == true,
              (flags.contains(.reachable) && !flags.contains(.connectionRequired)) == true
        else {
            return "notReachable"
        }
        if flags.contains(.connectionRequired) {
            return "notReachable"
        } else if flags.contains(.isWWAN) {
            return cellularType()
        } else {
            return "WiFi"
        }
    }
    
    /// 获取蜂窝数据类型
    func cellularType() -> String {
        let info = CTTelephonyNetworkInfo()
        var status: String
        
        if #available(iOS 12.0, *) {
            guard let dict = info.serviceCurrentRadioAccessTechnology,
                  let firstKey = dict.keys.first,
                  let statusTemp = dict[firstKey] else {
                return "notReachable"
            }
            status = statusTemp
        } else {
            guard let statusTemp = info.currentRadioAccessTechnology else {
                return "notReachable"
            }
            status = statusTemp
        }
        
        if #available(iOS 14.1, *) {
            if status == CTRadioAccessTechnologyNR || status == CTRadioAccessTechnologyNRNSA {
                return "5G"
            }
        }
        
        switch status {
        case CTRadioAccessTechnologyGPRS,
            CTRadioAccessTechnologyEdge,
        CTRadioAccessTechnologyCDMA1x:
            return "2G"
        case CTRadioAccessTechnologyWCDMA,
            CTRadioAccessTechnologyHSDPA,
            CTRadioAccessTechnologyHSUPA,
            CTRadioAccessTechnologyeHRPD,
            CTRadioAccessTechnologyCDMAEVDORev0,
            CTRadioAccessTechnologyCDMAEVDORevA,
        CTRadioAccessTechnologyCDMAEVDORevB:
            return "3G"
        case CTRadioAccessTechnologyLTE:
            return "4G"
        default:
            return "notReachable"
        }
    }
}
